package com.eric.similarity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import com.eric.similarity.pipe.Pipe;

public abstract class Similarity<K,S> {
	protected Double THRESHOLD = 0.5;
	protected HashMap<Entry<K,K>,S> Sim = new HashMap<Entry<K,K>,S>();
	protected HashMap<Entry<K,K>,S> ConfidentMap = new HashMap<Entry<K,K>,S>();
	protected HashMap<K,K> SimMap = new HashMap<K,K>();
	
	protected Pipe<K> pipe;
	
	public Similarity (String path) throws IOException {
//		SimOfFiles(path);
//		pipe = new FilePipe<K>(path);
	}
	
	public void run () {
		if (pipe != null) {
			calSim ();
			ConfidentMap();
			SimMap();
		}
	}
	
	public void setPipe (Pipe<K> pipe) {
		this.pipe = pipe;
	}
	
	public Similarity () {}
	
	public void SimOfFiles (String path) throws IOException{}
	
	public HashMap<K,K> getSimMap () {
		return SimMap;
	}
	
	public HashMap<Entry<K,K>,S> getSim () {
		return Sim;
	}
	
	public HashMap<Entry<K,K>,S> getConfidentMap () {
		return ConfidentMap;
	}
	
	public void ConfidentMap () {
		Iterator<Entry<Entry<K, K>, S>> it = Sim.entrySet().iterator();
		while (it.hasNext()) {
			Entry<Entry<K,K>,S> entry = it.next();
			if ((Double)entry.getValue() > THRESHOLD) ConfidentMap.put(entry.getKey(), entry.getValue());
		}
	}
	
	public void calSim () {
		pipe.getMap();
		Iterator<Entry<Entry<K,K>,Entry<K,K>>> it = pipe.getMap().entrySet().iterator(); 
		while (it.hasNext()) {
			Entry<Entry<K, K>, Entry<K, K>> entry = it.next();
			K doc1 = entry.getKey().getKey();
			K doc2 = entry.getKey().getValue();
			K content1 = entry.getValue().getKey();
			K content2 = entry.getValue().getValue();
			putSim (doc1,doc2,content1,content2);
		}
	}
	
	public abstract void putSim (K file1,K file2,K content1,K content2);
	
	public void setThresh (Double thresh) {
		this.THRESHOLD = thresh;
	}
	
	public void SimMap () {
		Iterator<Entry<Entry<K, K>, S>> it = ConfidentMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry<K, K> entry = it.next().getKey();
			SimMap.put(entry.getKey(), entry.getValue());
		}
	}
	
	public StringBuilder File2StringBuilder (File file) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		return sb;
	}
}
